home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1994 August / August CD.bin / Shareware / Education / numericalmethods Folder / chap_9 / rk4.m < prev    next >
Encoding:
Text File  |  1994-06-05  |  667 b   |  26 lines  |  [MATF/MATL]

  1. function [T,Y] = rk4(f,a,b,ya,m)
  2. % [T,Y] = rk4(f,a,b,ya,m)
  3. % Runge-Kutta solution for y' = f(t,y) with y(a) = ya.
  4. % f  is the function, input.
  5. % a  is the left endpoint, input.
  6. % b  is the right endpoint, input.
  7. % ya is the initial condition, input.
  8. % m  is the number of steps, input.
  9. % T  is the vector of abscissas, output.
  10. % Y  is the vector of ordinates, output.
  11. h = (b - a)/m;
  12. T = zeros(1,m+1);
  13. Y = zeros(1,m+1);
  14. T(1) = a;
  15. Y(1) = ya;
  16. for j=1:m,
  17.   tj = T(j);
  18.   yj = Y(j);
  19.   k1 = h*feval(f,tj,yj);
  20.   k2 = h*feval(f,tj+h/2,yj+k1/2);
  21.   k3 = h*feval(f,tj+h/2,yj+k2/2);
  22.   k4 = h*feval(f,tj+h,yj+k3);
  23.   Y(j+1) = yj + (k1 + 2*k2 + 2*k3 + k4)/6;
  24.   T(j+1) = a + h*j;
  25. end
  26.